import { readJson, writeJSON } from '../util/PromiseJson.js'
import path from 'path'
import __dirname from '../util/dirname.js'
import fs from 'fs'
import { promisify } from 'util'
const readdir = promisify(fs.readdir)

const database = path.resolve(__dirname,'../data/robots/robots.json')
const big_sprite_templete = 'http://127.0.0.1:9600/assets/images/robotImg/{$}'
const sprite_templete = 'http://127.0.0.1:9600/assets/images/robots/{$}'

const getRobotsListByPage = async (req,res)=>{
  const { page, size ,search} = req.query
  let robots = await readJson(database)
  if(search) {
    robots = robots.filter(e=>e.name.includes(search))
  }
  const start = (page - 1) * size
  let end = start + size
  end = end >= robots.length ? robots.length : end
  const sub = robots.slice(start, end)
  sub.forEach(e => {
    e.bigSprite = big_sprite_templete.replace('{$}', e.bigSprite)
    e.sprite = sprite_templete.replace('{$}', e.sprite)
  })

  res.send({ code: 200, msg: 'ok', data: sub, total: robots.length, next: parseInt(page) + 1 })
}


const spriteTexture = '/assets/images/robots/'
const spriteDir = path.join(__dirname,'../assets/images/robots')
const getSprites = async (req, res) => {
  const result = await readdir(spriteDir)
  const data = result.map(e => res.res_baseUrl + spriteTexture + e)
  res.send({
    code: 200,
    msg: 'ok',
    data
  })
}

const bigSpriteTexture = '/assets/images/robotImg/'
const bigSpriteDir = path.join(__dirname,'../assets/images/robotImg')
const getBigSprites = async (req, res) => {
  const result = await readdir(bigSpriteDir)
  const data = result.map(e => res.res_baseUrl + bigSpriteTexture + e)
  res.send({
    code: 200,
    msg: 'ok',
    data
  })
}

const saveRobot = async (req,res)=>{
  const {data} = req.body
  const robots = await readJson(database)
  // console.log(robots);
  const target = robots.find(e=>e.id == data.id)
  if(!target){
    return res.send({code:400,msg:'参数不正确'})
  }
  data.bigSprite = data.bigSprite.slice(data.bigSprite.lastIndexOf('/') + 1)
  data.sprite = data.sprite.slice(data.sprite.lastIndexOf('/') + 1)
  Object.assign(target,data)
  await writeJSON(database,JSON.stringify(robots))
  res.send({code:200,msg:'ok'})
}

export {getRobotsListByPage,getSprites,getBigSprites ,saveRobot}